﻿@namespace BootstrapBlazor.Components
@typeparam TModel
@inherits BootstrapComponentBase

<CascadingValue Value="@EditorItems" IsFixed="true">
    @FieldItems?.Invoke(Model)
</CascadingValue>

@if (FirstRender)
{
    <div class="ef-loading">
        <Spinner Color="Color.Primary" />
    </div>
}
else
{
    <div class="form-body">
        <CascadingValue Value="this" Name="EidtorForm">
            @if(ShowUnsetGroupItemsOnTop)
            {
                if (UnsetGroupItems.Any())
                {
                    @RenderUnsetGroupItems
                }
                @foreach (var g in GroupItems)
                {
                    @RenderGroupItems(g)
                }
            }
            else
            {
                @foreach (var g in GroupItems)
                {
                    @RenderGroupItems(g)
                }
                if (UnsetGroupItems.Any())
                {
                    @RenderUnsetGroupItems
                }
            }
        </CascadingValue>
    </div>
    @if (Buttons != null)
    {
        <div class="form-footer">
            @Buttons
        </div>
    }
}

@code
{
    RenderFragment RenderUnsetGroupItems =>
    @<div class="@FormClassString">
        @foreach (var item in UnsetGroupItems)
        {
            var render = GetRenderTemplate(item);
            @if (render != null)
            {
                @render(Model)
            }
            else
            {
                <div class="@GetCssString(item)">
                    @AutoGenerateTemplate(item)
                </div>
            }
        }
    </div>;

    RenderFragment<KeyValuePair<string, IOrderedEnumerable<IEditorItem>>> RenderGroupItems => g =>
    @<GroupBox Title="@g.Key">
        <div class="@FormClassString">
            @foreach (var item in g.Value)
            {

                var render = GetRenderTemplate(item);
                @if (render != null)
                {
                    @render(Model)
                }
                else
                {
                    <div class="@GetCssString(item)">
                        @AutoGenerateTemplate(item)
                    </div>
                }
            }
        </div>
    </GroupBox>;
}
